package com.lagou.edu.service.impl;

import com.alibaba.fastjson.JSON;
import com.lagou.edu.dao.LagouEmailDao;
import com.lagou.edu.dao.LagouTokenDao;
import com.lagou.edu.pojo.LagouEmail;
import com.lagou.edu.pojo.LagouToken;
import com.lagou.edu.service.LagouCodeService;
import com.lagou.edu.service.LagouUserService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.UUID;

@Service(version = "2.7.3")
public class LagouUserServiceImpl implements LagouUserService {

    @Autowired
    private LagouTokenDao lagouTokenDao;

    @Autowired
    private LagouEmailDao lagouEmailDao;

//    @Autowired
//    private LagouCodeServiceFeignClient lagouCodeServiceFeignClient;

    @Reference(check = false,version = "2.7.3")
    private LagouCodeService lagouCodeService;

    @Override
    public String register(String email, String password, String code) {
        //判断是否注册
        if (!isRegistered(email)) {
            return null;
        }

        //判断验证码是否过期
        int validateCode = lagouCodeService.validate(email, code);
        if (validateCode != 0) {
            return null;
        }

        //存放email信息
        LagouEmail lagouEmail = new LagouEmail();
        lagouEmail.setEmail(email);
        lagouEmail.setPassword(password);
        lagouEmailDao.save(lagouEmail);

        //存放token信息
        LagouToken token = new LagouToken();
        token.setEmail(email);
        token.setToken(UUID.randomUUID().toString());
        return JSON.toJSONString(lagouTokenDao.save(token));
    }

    @Override
    public boolean isRegistered(String email) {
        LagouEmail lagouEmail = lagouEmailDao.findFirstByEmail(email);
        return lagouEmail == null;
    }

    @Override
    public String login(String email, String password) {
        //判断邮件是否存在
        LagouEmail lagouEmail = lagouEmailDao.findFirstByEmail(email);
        if (lagouEmail == null) {
            return null;
        }
        //判断密码是否正确
        if (!lagouEmail.getPassword().equalsIgnoreCase(password)) {
            return null;
        }
        LagouToken lagouToken = new LagouToken();
        lagouToken.setEmail(email);
        lagouToken.setToken(UUID.randomUUID().toString());
        return JSON.toJSONString(lagouTokenDao.save(lagouToken));
    }

    @Override
    public String getEmailByToken(String token) {
        LagouToken lagouToken = lagouTokenDao.findFirstByToken(token);
        return token == null ? "EMAIL NOT FOUND" : lagouToken.getEmail();
    }
}
